<template>
  <el-drawer
    :model-value="isShowDetail"
    size="380px"
    @close="close"
    :close-on-click-modal="false"
  >
    <template #header="{}">
      <div class="flex items-center justify-start">
        <div class="flex items-center justify-center flex-1">
          <p>{{ drawerTitle }}</p>
        </div>
      </div>
    </template>
    <div v-loading="loading" class="drawerContent">
      <el-card class="customCard">
        <div class="flex justify-end text-[#e54c5f] text-sm mt-2">
          <el-popover placement="bottom-end" :width="200" trigger="click">
            <template #reference>
              <span class="flex items-center cursor-pointer"
                >{{ $t("费用说明")
                }}<el-icon class="ml-1" size="18"><QuestionFilled /></el-icon
              ></span>
            </template>
            <p
              class="mb-2"
              v-html="
                state.detailInfo.tips
                  ? state.detailInfo.tips?.replace(/\n/g, '<br>')
                  : '--'
              "
            ></p>
          </el-popover>
        </div>
        <el-divider style="margin: 10px 0" />
        <div class="flex flex-col items-start justify-start">
          <span class="text-[#7F7F7F] mb-2">{{ $t("卡片类型") }}</span>
          <span>{{ state.detailInfo.category_name }}</span>
        </div>
        <div class="flex flex-col items-start justify-start mt-2">
          <span class="text-[#7F7F7F] mb-2">{{ $t("卡片状态") }}</span>
          <span>
            <el-tag
              :type="
                getCardStatusName(state.detailInfo.card_status)
                  ? getCardStatusName(state.detailInfo.card_status)?.type
                  : 'info'
              "
            >
              {{
                getCardStatusName(state.detailInfo.card_status)
                  ? getCardStatusName(state.detailInfo.card_status)?.name
                  : state.detailInfo.card_status
              }}
            </el-tag></span
          >
        </div>
        <div class="flex flex-col items-start justify-start mt-2">
          <span class="text-[#7F7F7F] mb-2">{{ $t("卡片别名") }}</span>
          <span>{{ state.detailInfo.nick_name }}</span>
        </div>
        <div class="flex flex-col items-start justify-start mt-2">
          <span class="text-[#7F7F7F] mb-2">{{ $t("卡片额度") }}</span>
          <span
            >{{ numberToCurrencyNo(state.totalAmount) }}
            {{ state.detailInfo.currency }}</span
          >
        </div>
      </el-card>
      <div
        class="flex justify-start mt-4 cardInfo"
        :class="
          state.detailInfo.brand == 'VISA'
            ? 'imgVisa'
            : capitalizeFirstLetter(state.detailInfo.brand) == 'Master'
            ? 'imgMaster'
            : ''
        "
      >
        <div
          class="left w-[90px] flex flex-col justify-between items-center py-6"
        >
          <div class="flex justify-center items-center h-[20px] text-[#fff]">
            <span
              class="mr-2 dot"
              :class="{
                greenColor: state.detailInfo.card_status == 'ACTIVE',
              }"
            ></span
            ><span class="text-sm">{{
              state.detailInfo.card_status == "ACTIVE"
                ? $t("卡-可用")
                : $t("不可用")
            }}</span>
          </div>
        </div>
        <div class="right flex-1 py-6 ml-6 text-sm text-[#fff]">
          <div class="detailRow">
            <span class="rowName"
              >{{ $t("卡片号码") }}
              <el-icon
                class="ml-3 cursor-pointer hideIcon"
                @click="reveal(!state.isShowCard)"
                v-if="state.cardInfo.card_number"
              >
                <View v-if="state.isShowCard" />
                <Hide v-else /> </el-icon
            ></span>
            <span class="flex items-center justify-start rowValue"
              >{{ state.cardInfo.card_number }}
              <span>
                <el-icon
                  v-if="state.isShowCard"
                  size="15"
                  class="mt-1 ml-2 cursor-pointer"
                  @click="copyToClipboard"
                >
                  <CopyDocument /> </el-icon
              ></span>
            </span>
          </div>
          <div class="detailRow">
            <span class="rowName">{{ $t("月/年") }}</span>
            <span class="rowValue"> {{ state.cardInfo.card_time }}</span>
          </div>
          <div class="detailRow">
            <span class="rowName">{{ $t("安全码") }}</span>
            <span class="rowValue"> {{ state.cardInfo.cvv }}</span>
          </div>
          <p class="realName">{{ state.detailInfo?.name_on_card }}</p>
        </div>
      </div>
      <div class="flex items-center justify-center mt-4">
        <el-button
          @click="reveal(!state.isShowCard)"
          v-if="state.cardInfo.card_number"
          class="lookBtn"
        >
          <el-icon class="mr-2" color="#e54c5f">
            <View v-if="!state.isShowCard" />
            <Hide v-else /> </el-icon
          >{{
            state.isShowCard ? $t("隐藏卡片详情") : $t("显示卡片详情")
          }}</el-button
        >
      </div>
      <el-card class="mt-4 customCard" v-if="state.detailInfo.show_limit">
        <template #header>
          <div class="card-header">
            <span>{{ $t("刷卡限额") }}</span>
          </div>
        </template>
        <div>
          <div class="flex flex-col items-start justify-start mt-2">
            <span class="text-[#7F7F7F] mb-2">{{ $t("交易限额") }}</span>
            <span
              >{{ numberToCurrencyNo(state.totalAmount) }}
              {{ state.detailInfo.currency }}
            </span>
          </div>
          <div v-for="item of state.limits" class="mt-2 text-sm">
            <h5 class="text-[#7F7F7F] mb-2">{{ item.interval_name }}</h5>
            <p class="mb-2">
              {{ numberToCurrencyNo(item.amount) }}
              {{ state.detailInfo.currency }}
              {{ $t("限额") }}
            </p>
            <!-- 单笔不需要 -->
            <el-progress
              v-if="item.interval !== 'PER_TRANSACTION'"
              :percentage="percentage(item)"
              status="exception"
              :show-text="false"
              :max="item.amount"
            />
            <p class="mt-2" v-if="item.interval !== 'PER_TRANSACTION'">
              {{ $t("剩余")
              }}{{
                numberToCurrencyNo(Number(item.amount) - Number(item.remaining))
              }}
              {{ state.detailInfo.currency }}
            </p>
          </div>
        </div>
      </el-card>
      <el-card class="mt-4 customCard">
        <template #header>
          <div class="flex justify-between card-header">
            <span>{{ $t("卡片信息") }}</span>
            <span
              ><el-icon
                size="15"
                class="mt-1 ml-2 cursor-pointer"
                @click="copy"
              >
                <CopyDocument /> </el-icon
            ></span>
          </div>
        </template>
        <div>
          <div>
            <div class="flex flex-col items-start justify-start mt-2">
              <span class="text-[#7F7F7F] mb-2">{{ $t("卡-持卡人姓名") }}</span>
              <span>
                {{ state.detailInfo?.name_on_card }}
              </span>
            </div>
            <div class="flex flex-col items-start justify-start mt-2">
              <span class="text-[#7F7F7F] mb-2">{{ $t("姓氏") }}</span>
              <span>
                {{ state.detailInfo?.primary_contact?.last_name }}
              </span>
            </div>
            <div class="flex flex-col items-start justify-start mt-2">
              <span class="text-[#7F7F7F] mb-2">{{ $t("名字") }}</span>
              <span>
                {{ state.detailInfo?.primary_contact?.first_name }}
              </span>
            </div>
            <div class="flex flex-col items-start justify-start mt-2">
              <span class="text-[#7F7F7F] mb-2">{{ $t("邮箱") }}</span>
              <span>
                {{ state.detailInfo?.primary_contact?.email }}
              </span>
            </div>
            <div class="flex flex-col items-start justify-start mt-2">
              <span class="text-[#7F7F7F] mb-2">{{ $t("电话号码") }}</span>
              <span>
                {{ state.detailInfo?.primary_contact?.area_code }} -
                {{ state.detailInfo?.primary_contact?.mobile_number }}
              </span>
            </div>
            <div class="flex flex-col items-start justify-start mt-2">
              <span class="text-[#7F7F7F] mb-2">{{
                $t("是否支持3D验证")
              }}</span>
              <span>
                {{
                  state.detailInfo.allow_3ds == 1
                    ? $t("是")
                    : state.detailInfo.allow_3ds == 0
                    ? $t("否")
                    : "--"
                }}
              </span>
            </div>
            <div class="flex flex-col items-start justify-start mt-2">
              <span class="text-[#7F7F7F] mb-2">{{ $t("创建日期") }}</span>
              <span>
                {{ formatDates(state.detailInfo.createtime) }}
              </span>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    <template #footer="{}">
      <div class="flex items-center justify-start">
        <div class="flex items-center justify-end flex-1 mr-10 cardOperate">
          <div class="w-[220px]">
            <el-popover
              placement="top-end"
              width="auto"
              trigger="click"
              v-model:visible="visible"
              v-if="setCardBtnList.length"
              append-to-body="false"
            >
              <template #reference>
                <el-button
                  type="primary"
                  :plain="true"
                  class="manageBtn plainButton"
                  >{{ $t("管理卡片") }}</el-button
                >
              </template>
              <div class="flex flex-col px-3">
                <div
                  class="flex justify-between items-center cursor-pointer mb-2 text-[#333]"
                  @click="item.click()"
                  v-for="(item, index) of setCardBtnList"
                  :key="index"
                >
                  <span>{{ item.name }}</span>
                </div>
              </div>
            </el-popover>
          </div>
        </div>
      </div>
    </template>
  </el-drawer>
  <SetLimit
    :isShowLimit="isShowLimit"
    :totalAmount="state.totalAmount"
    :detailInfo="state.detailInfo"
    :cardLimits="state.cardLimits"
    :cardId="state.detailInfo.card_id"
    @close="
      () => {
        isShowLimit = false;
        visible = false;
        closeTriggeredByLimit = true;
      }
    "
    @closeAll="
      () => {
        isShowLimit = false;
        visible = false;
        if (!closeTriggeredByLimit) {
          isShowDetail = false;
          emits('close');
        }
        closeTriggeredByLimit = false;
      }
    "
  ></SetLimit>
  <Recharge
    :isShowRecharge="isShowRecharge"
    :cardId="state.detailInfo.card_id"
    :isHavePassword="isHavePassword"
    :assetType="state.detailInfo.asset_type"
    @close="
      () => {
        isShowRecharge = false;
        visible = false;
        closeTriggeredByRecharge = true;
      }
    "
    @closeAll="
      () => {
        isShowRecharge = false;
        visible = false;
        if (!closeTriggeredByRecharge) {
          isShowDetail = false;
          emits('close');
        }
        closeTriggeredByRecharge = false;
      }
    "
  />
  <Withdraw
    :isShowWithdraw="isShowWithdraw"
    :cardId="state.detailInfo.card_id"
    :assetType="state.detailInfo.asset_type"
    :isHavePassword="isHavePassword"
    @close="
      () => {
        isShowWithdraw = false;
        visible = false;
        closeTriggeredByWithdraw = true;
      }
    "
    @closeAll="
      () => {
        isShowWithdraw = false;
        visible = false;
        if (!closeTriggeredByWithdraw) {
          isShowDetail = false;
          emits('close');
        }
        closeTriggeredByWithdraw = false;
      }
    "
  />
  <Record
    :isShowRecord="isShowRecord"
    :cardId="state.detailInfo.card_id"
    :assetType="state.detailInfo.asset_type"
    @close="
      () => {
        isShowRecord = false;
        visible = false;
        closeTriggeredByRecord = true;
      }
    "
    @closeAll="
      () => {
        isShowRecord = false;
        visible = false;
        if (!closeTriggeredByRecord) {
          isShowDetail = false;
          emits('close');
        }
        closeTriggeredByRecord = false;
      }
    "
  />
</template>
<script setup>
import { ref, watch, reactive, computed, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import {
  numberToCurrencyNo,
  generateMaskedString,
  formatDates,
} from "@/utils/utils";
import { GetNewMerchantInfo } from "@/api/merchant/index";
import Recharge from "./recharge.vue";
import Withdraw from "./withdraw.vue";
import Record from "./record.vue";
import SetLimit from "./setLimit.vue";
import { ElMessageBox, ElMessage } from "element-plus";
import {
  GetCardsDetail,
  GetCardsLimits,
  setCard,
  getCardSensitive,
  setCardLimits,
  GetCardsConfig,
} from "@/api/card";
const router = useRouter();
const route = useRoute();
const loading = ref(false);

const props = defineProps({
  isShowDetail: {
    type: Boolean,
    default: false,
  },
  cardId: {
    type: String,
    default: "",
  },
  assetType: {
    type: String,
    default: "",
  },
});

const emits = defineEmits(["close", "refreshList"]);
const close = () => {
  document.querySelector(".el-drawer__body").scrollTo(0, 0);
  emits("close");
};

const drawerTitle = ref(t("卡片详情"));

const state = reactive({
  limitDrawer: false,
  totalAmount: "",
  cardLimits: [],
  cardInfo: {},
  detailInfo: {},
  searchConditions: [
    {
      amount: "",
      interval: "",
      tips: "",
    },
  ],
  limits: {},
  isShowCard: false,
  dayLy_amount: 0,
  week_amount: 0,
  month_amount: 0,
});

const closeTriggeredByRecord = ref(false);
const closeTriggeredByRecharge = ref(false);
const closeTriggeredByWithdraw = ref(false);
const closeTriggeredByLimit = ref(false);
const isShowLimit = ref(false);

// 按钮list
const setCardBtnList = computed(() => {
  let btnList = ref([]);
  // 判断是否是线下开卡,如果是非活跃状态按钮都不展示 FAILED
  if (state.detailInfo.offline) {
    if (
      state.detailInfo.card_status === "ACTIVE" ||
      (state.detailInfo.card_status !== "CLOSED" &&
        state.detailInfo.card_status !== "PENDING" &&
        state.detailInfo.card_status !== "FAILED")
    ) {
      btnList.value = [
        {
          key: "record",
          name: `${t("账户流水")}`,
          color: "rgba(52, 152, 219, 1)",
          click: () => {
            record();
          },
        },
        {
          key: "recharge",
          name: `${t("充值")}`,
          color: "rgba(93, 109, 126, 1)",
          click: () => {
            recharge();
          },
        },
        {
          key: "withdraw",
          name: `${t("提现")}`,
          color: "rgba(93, 109, 126, 1)",
          click: () => {
            withdraw();
          },
        },
        {
          key: "signOutCard",
          name: `${t("注销卡片")}`,
          click: () => {
            signOutCard();
          },
        },
        {
          key: "frozen",
          name: `${
            state.detailInfo.card_status === "INACTIVE"
              ? t("解冻卡片")
              : t("冻结卡片")
          }`,
          click: () => {
            frozen(
              state.detailInfo.card_status === "INACTIVE"
                ? "ACTIVE"
                : "INACTIVE"
            );
          },
        },
        // {
        //   key: "reveal",
        //   name: `${state.isShowCard ? t("显示卡片详情") : t("隐藏卡片详情")}`,
        //   click: () => {
        //     reveal(state.isShowCard ? true : false);
        //   },
        // },
        {
          key: "recharge",
          name: `${t("充值")}`,
          click: () => {
            recharge();
          },
        },
        {
          key: "withdraw",
          name: `${t("提现")}`,
          click: () => {
            withdraw();
          },
        },
      ];
    } else {
      if (state.detailInfo.card_status == "CLOSED") {
        btnList.value = [
          {
            key: "record",
            name: `${t("账户流水")}`,
            color: "rgba(52, 152, 219, 1)",
            click: () => {
              record();
            },
          },
        ];
      } else {
        btnList.value = [];
      }
    }
  } else {
    if (
      state.detailInfo.card_status === "CLOSED" ||
      state.detailInfo.card_status === "FAILED"
    ) {
      if (state.detailInfo.card_status == "CLOSED") {
        btnList.value = [
          {
            key: "record",
            name: `${t("账户流水")}`,
            color: "rgba(52, 152, 219, 1)",
            click: () => {
              record();
            },
          },
        ];
      } else {
        btnList.value = [];
      }
    } else {
      let arr = ["ACTIVE", "PENDING", "INACTIVE"];
      let arr1 = ["ACTIVE", "PENDING"];
      if (arr.includes(state.detailInfo.card_status)) {
        btnList.value = [
          {
            key: "record",
            name: `${t("账户流水")}`,
            color: "rgba(52, 152, 219, 1)",
            click: () => {
              record();
            },
          },
          {
            key: "recharge",
            name: `${t("充值")}`,
            color: "rgba(93, 109, 126, 1)",
            click: () => {
              recharge();
            },
          },
          {
            key: "withdraw",
            name: `${t("提现")}`,
            color: "rgba(93, 109, 126, 1)",
            click: () => {
              withdraw();
            },
          },
          {
            key: "signOutCard",
            name: `${t("注销卡片")}`,
            click: () => {
              signOutCard();
            },
          },
          {
            key: "frozen",
            name: `${
              state.detailInfo.card_status === "INACTIVE"
                ? t("解冻卡片")
                : t("冻结卡片")
            }`,
            click: () => {
              frozen(
                state.detailInfo.card_status === "INACTIVE"
                  ? "ACTIVE"
                  : "INACTIVE"
              );
            },
          },
        ];
      }
      if (arr1.includes(state.detailInfo.card_status)) {
        btnList.value = [
          {
            key: "record",
            name: `${t("账户流水")}`,
            color: "rgba(52, 152, 219, 1)",
            click: () => {
              record();
            },
          },
          {
            key: "recharge",
            name: `${t("充值")}`,
            color: "rgba(93, 109, 126, 1)",
            click: () => {
              recharge();
            },
          },
          {
            key: "withdraw",
            name: `${t("提现")}`,
            color: "rgba(93, 109, 126, 1)",
            click: () => {
              withdraw();
            },
          },
          {
            key: "signOutCard",
            name: `${t("注销卡片")}`,
            click: () => {
              signOutCard();
            },
          },
          {
            key: "frozen",
            name: `${
              state.detailInfo.card_status === "INACTIVE"
                ? t("解冻卡片")
                : t("冻结卡片")
            }`,
            click: () => {
              frozen(
                state.detailInfo.card_status === "INACTIVE"
                  ? "ACTIVE"
                  : "INACTIVE"
              );
            },
          },
          {
            key: "editCard",
            name: `${t("修改卡片")}`,
            click: () => {
              editCard();
            },
          },
          {
            key: "setLimit",
            name: `${t("设置限额")}`,
            click: () => {
              setLimit();
            },
          },
        ];
      }
    }
  }
  // 判断是否可以充值提现
  if (state.detailInfo.allow_in == 0) {
    let index = btnList.value.findIndex((item) => item.key == "recharge");
    if (index > 0) {
      btnList.value.splice(index, 1);
    }
  }
  if (state.detailInfo.allow_out == 0) {
    let index = btnList.value.findIndex((item) => item.key == "withdraw");
    if (index > 0) {
      btnList.value.splice(index, 1);
    }
  }
  if (state.detailInfo.allow_limit == 0) {
    let index = btnList.value.findIndex((item) => item.key == "setLimit");
    if (index > 0) {
      btnList.value.splice(index, 1);
    }
  }
  return btnList.value;
});

const visible = ref(false);

// 注销卡
const signOutCard = () => {
  // 关闭 Popover
  visible.value = false;
  ElMessageBox.confirm(
    `${t(
      "注销后的卡片将无法被替换，也无法被用于新的交易。待处理交易仍可能通过处理。此操作无法撤销!"
    )}`,
    `${t("您即将注销这张卡片!")}`,
    {
      confirmButtonText: `${t("确认注销")}`,
      cancelButtonText: `${t("取消")}`,
    }
  )
    .then(async () => {
      loading.value = true;
      const res = await setCard({
        card_id: state.detailInfo.card_id,
        card_status: "CLOSED",
      });
      if (res) {
        ElMessage({
          type: "success",
          message: state.detailInfo.offline
            ? t("您已申请注销卡片，请等待审核")
            : t("此卡已注销"),
        });
        loading.value = false;
        router.replace({
          path: "/card/management",
        });
      }
    })
    .catch((error) => {
      // 判断如果接口返回数据了，则不展示取消文案
      if (error === "cancel") {
        ElMessage({
          type: "info",
          message: `${t("取消")}`,
        });
      }
      loading.value = false;
    });
};

// 冻结
const frozen = async (type) => {
  // 关闭 Popover
  visible.value = false;
  try {
    loading.value = true;
    const res = await setCard({
      card_id: state.detailInfo.card_id,
      card_status: type,
    });
    loading.value = false;
    if (res) {
      let text = "";
      // 是否线下开卡判断
      if (state.detailInfo.offline) {
        text =
          type === "ACTIVE"
            ? t("您已申请解冻卡片，请等待审核")
            : t("您已申请冻结卡片，请等待审核");
      } else {
        text =
          type === "ACTIVE"
            ? t("您的卡片已被激活，可立即使用")
            : t("您的卡片已被冻结,已无法使用");
      }
      ElMessage({
        type: "success",
        message: text,
      });
      getCardsDetail();
    }
  } catch {
    loading.value = false;
  }
};

// 修改卡
const editCard = () => {
  // 关闭 Popover
  visible.value = false;
  router.replace({
    path: "/card/management/editCard",
    query: { card_id: props.cardId },
  });
};

// 设置限额
const setLimit = () => {
  // 关闭 Popover
  visible.value = false;
  isShowLimit.value = true;
  // 默认不展示10000每笔
  if (
    state.limits.length === 1 &&
    state.limits[0].amount === 10000 &&
    state.limits[0].interval === "PER_TRANSACTION"
  ) {
    state.searchConditions = state.searchConditions;
  } else {
    if (state.limits.length > 0) {
      state.searchConditions = state.limits.map((item) => {
        return {
          amount: item.amount,
          interval: item.interval,
        };
      });
    }
  }
  state.limitDrawer = true;
};

const capitalizeFirstLetter = (str) => {
  if (str) {
    return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
  }
};

const isShowRecord = ref(false);

const record = () => {
  // 关闭 Popover
  visible.value = false;
  isShowRecord.value = true;
};

const isShowRecharge = ref(false);
const isShowWithdraw = ref(false);

const recharge = () => {
  // 关闭 Popover
  visible.value = false;
  isShowRecharge.value = true;
  getUserInfo();
};

const withdraw = () => {
  // 关闭 Popover
  visible.value = false;
  isShowWithdraw.value = true;
  getUserInfo();
};

const isHavePassword = ref();
const getUserInfo = async () => {
  const res = await GetNewMerchantInfo();
  isHavePassword.value = res.is_set_trade_password;
};

watch(
  () => props.isShowDetail,
  async (val) => {
    if (val) {
      await getCardsDetail();
      await getCardsConfig();
      await getCardsLimits();
    }
  }
);

const copyToClipboard = () => {
  let text = [
    `卡片号码：${state.cardInfo.card_number}\n月/年：${state.cardInfo.card_time}\n安全码：${state.cardInfo.cvv}`,
  ];
  copyCustomContent(text);
};

const copy = () => {
  let text = [
    `持卡人姓名：${state.detailInfo.name_on_card}\n姓氏：${
      state.detailInfo.primary_contact?.last_name
    }\n名字：${state.detailInfo.primary_contact?.first_name}\n邮箱：${
      state.detailInfo.primary_contact?.email
    }\n电话号码：${state.detailInfo.primary_contact?.area_code} - ${
      state.detailInfo.primary_contact?.mobile_number
    }\n是否支持3D验证：${
      state.detailInfo.allow_3ds == 1
        ? t("是")
        : state.detailInfo.allow_3ds == 0
        ? t("否")
        : "--"
    }\n创建日期：${formatDates(state.detailInfo.createtime)}`,
  ];
  copyCustomContent(text);
};

const copyCustomContent = (text) => {
  const item = new ClipboardItem({
    "text/plain": new Blob(text, {
      type: "text/plain",
    }),
  });
  navigator.clipboard
    .write([item])
    .then(function () {
      showSuccessMessage("复制成功");
    })
    .catch(function (error) {
      console.error("复制失败", error);
    });
};

const showSuccessMessage = (message) => {
  ElMessage({
    showClose: true,
    message: message,
    type: "success",
  });
};

const cardStatus = computed(() => {
  return [
    { key: 1, name: `${t("未激活")}`, value: "PENDING", type: "warning" },
    { key: 2, name: `${t("活跃")}`, value: "ACTIVE", type: "success" },
    { key: 3, name: `${t("已冻结")}`, value: "INACTIVE", type: "danger" },
    // { key: 4, name: "已挂失", value: "LOST", type: "danger" },
    // { key: 5, name: "已被盗", value: "STOLEN", type: "danger" },
    { key: 6, name: `${t("已注销")}`, value: "CLOSED", type: "info" },
    { key: 7, name: `${t("创建失败")}`, value: "FAILED", type: "danger" },
  ];
});

// 卡片状态
const getCardStatusName = (status) => {
  return cardStatus.value.find((i) => status === i.value);
};

// 年月星号
const maskDate = (dateString) => {
  const [month, year] = dateString.split("/"); // 替换月份和年份的每个数字为星号
  const maskedMonth = month.replace(/\d/g, "*");
  const maskedYear = year.replace(/\d/g, "*"); // 重新组合并返回带有分隔符的星号字符串
  return `${maskedMonth}/${maskedYear}`;
};

const cardInfo = () => {
  return {
    card_number: generateMaskedString() + state.detailInfo.card_number,
    card_time: maskDate("12 / 2024"),
    cvv: "****",
  };
};

// 卡片详情
const getCardsDetail = async () => {
  try {
    loading.value = true;
    const data = (await GetCardsDetail({ card_id: props.cardId })) || {};
    state.detailInfo = data;
    state.cardInfo = cardInfo();
    state.totalAmount = data.total_amount || 0;
    loading.value = false;
  } catch {}
};

// 获取卡片限额
const getCardsLimits = async () => {
  try {
    const { limits } = await GetCardsLimits({ card_id: props.cardId });
    state.limits = limits || [];
  } catch (e) {
    console.log(e);
  }
};

const percentage = (item) => {
  if (item.remaining) {
    return ((item.amount - item.remaining) / item.amount) * 100;
  } else {
    return 0;
  }
};

// 卡片基本信息
const getCardsConfig = async () => {
  try {
    const { limits } = await GetCardsConfig();
    state.cardLimits = limits || [];
  } catch (e) {
    console.log(e);
  }
};

// 显示卡详情
const reveal = async (isShow) => {
  if (isShow) {
    try {
      loading.value = true;
      const data = await getCardSensitive({ card_id: props.cardId });
      loading.value = false;
      state.cardInfo = data;
      ElMessage.success(t("获取卡片详情成功"));
    } catch {
      loading.value = false;
    }
    state.cardInfo.card_time = `${state.cardInfo.expiry_month} / ${state.cardInfo.expiry_year}`;
    state.isShowCard = true;
  } else {
    state.cardInfo = cardInfo();
    state.isShowCard = false;
  }
};
</script>
<style lang="scss" scoped>
.detailRow {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  margin-bottom: 12px;

  .rowName {
    min-width: 30%;
    flex-shrink: 0;
    display: flex;
    align-items: center;
  }

  .rowValue {
    margin-top: 5px;
    word-break: break-all;
    text-align: right;
  }
}

.cardInfo {
  height: 250px;
  background: url("@/assets/images/详情默认卡面.png") no-repeat;
  background-position: center;
  background-size: 100% 100%;
  .dot {
    width: 8px;
    height: 8px;
    background-color: #d9001b;
    border-radius: 50%;
    display: inline-block;
  }
  .greenColor {
    background-color: #95f204;
  }
}
.imgVisa {
  height: 250px;
  background: url("@/assets/images/newVisa.png") no-repeat;
  background-position: center;
  background-size: 100% 100%;
}
.imgMaster {
  height: 250px;
  background: url("@/assets/images/newMaster.png") no-repeat;
  background-position: center;
  background-size: 100% 100%;
}
.lookBtn {
  color: #e54c5f;
}
.cardOperate {
  padding: 8px 0 10px;
  height: 100%;
}
.realName {
  width: 130px;
  white-space: normal;
}
</style>
